﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.BusinessLogic.Product;
using OpenSoftStore.Orm.View;
using OpenSoftStore.BusinessLogic.Admin;
using OpenSoftStore.BusinessLogic.Common;

namespace OpenSoftStore.Client.UIL.ManageProduct
{
    public partial class ProductOut : UserControl
    {
        private const string _ShopId = "b0def1a7-bf25-45f2-b65a-6dc586dbfc2c";
        private T_StoreIO storeIO;
        private T_StoreIOItem storeItem;
        private ProductLogic productBll;
        private AdminLogic adminBll;
        private ComboLogic comboBll;
        private List<V_StoreIOItem> storeItems;

        public Boolean Drog = false;
        public int Top = 0;
        public int Left = 0;

        public ProductOut()
        {
            productBll = new ProductLogic();
            adminBll = new AdminLogic();
            comboBll = new ComboLogic();
            storeItems = new List<V_StoreIOItem>();
            storeIO = new T_StoreIO();
            storeItem = new T_StoreIOItem();
            InitializeComponent();

            LoadControlData();

            SPACommon.SetDataGridStyle(dgvProduct);
            SPACommon.SetDataGridStyle(dgvProductOut);
        }
        private void ProductOut_Load(object sender, EventArgs e)
        {
            txtProductSearch.Focus();
            txtProductSearch.Select();
        }

        public void GetStoreIO(T_StoreIO store)
        {
            storeIO.Id = store.Id;
            switch (store.BuzType)
            {
                case "耗材":
                    rbExpend.Checked = true;
                    break;
                case "调拨调出":
                    rbTransfer.Checked = true;
                    break;
                case "向供应商退货":
                    rbReturn.Checked = true;
                    break;
                case "盘亏":
                    rbInventoryShortages.Checked = true;
                    break;
                default:
                    break;
            }

            txtOrder.Text = store.StroeIONo;
            cmbProvider.SelectedValue = store.BuzUserId;
            cmbAdmin.SelectedValue = store.AdminId;
            dtpOut.Value = store.AddTime;
            txtRemark.Text = store.Remark;
            storeItems = productBll.GetStoreItemView(" where S.StoreIOId='" + store.Id + "'").ToList();
            dgvProductOut.DataSource = storeItems;
        }

        private void LoadControlData()
        {
            cmbProvider.ValueMember = "Id";
            cmbProvider.DisplayMember = "Name";
            cmbProvider.DataSource = productBll.GetProvider();

            cmbAdmin.ValueMember = "Id";
            cmbAdmin.DisplayMember = "Name";
            cmbAdmin.DataSource = adminBll.GetAdminList();

            colPos.DisplayMember = "DisplayText";
            colPos.ValueMember = "Value1";
            var posItems = comboBll.GetComboByBuzType("Pos", _ShopId).ToList();
            colPos.DataSource = posItems;
            txtOrder.Text = productBll.GetCountNo("T_StoreIO", true);

            dgvProductOut.AutoGenerateColumns = false;
            dgvProduct.AutoGenerateColumns = false;
            dgvProduct.DataSource = productBll.GetProductList();
            lblProductCount.Text = dgvProduct.RowCount.ToString();
         
            //dgvProductOut.DefaultCellStyle.NullValue = posItems.Where(c => c.Value2 == "是").FirstOrDefault().DisplayText;
        }

        private void SetValue()
        {
            storeIO.StroeIONo = txtOrder.Text;
            storeIO.Remark = txtRemark.Text;
            storeIO.AdminId = cmbAdmin.SelectedValue.ToString();
            storeIO.AddTime = dtpOut.Value;
            storeIO.Type = "出库";
            storeIO.ProductKinds = dgvProductOut.Rows.Count;
            storeIO.BuzUserId = cmbProvider.SelectedValue.ToString();
            storeIO.ShopId = _ShopId;

        }

        private void txtSearch_KeyUp(object sender, KeyEventArgs e)
        {
            string whereStr = txtProductSearch.Text;
            if (rbSelect.Checked)
            {

                dgvProduct.DataSource = productBll.GetProductList(string.Format(" where P.Name like '{0}%' or P.ProductNo like '{0}%' or P.Model like '{0}%' or prov.Name like '{0}%' or T.Name like '{0}%'", whereStr));
            }
            else
            {
                dgvProduct.DataSource = productBll.GetProductList(" where E.BarCode='" + whereStr + "'");
            }
            lblProductCount.Text = dgvProduct.RowCount.ToString();
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            if (dgvProduct.Rows.Count == 0)
            {
                FormSysMessage.ShowMessage("目前没有添加一个商品，请添加完商品再出库！");
                return;
            }

            if (dgvProduct.SelectedRows[0] != null)
            {
                string id = dgvProduct.SelectedRows[0].Cells["productId"].Value.ToString();
                string name = dgvProduct.SelectedRows[0].Cells["name"].Value.ToString();
                decimal inPrice = Convert.ToDecimal(dgvProduct.SelectedRows[0].Cells["inPrice"].Value);
                string unit = dgvProduct.SelectedRows[0].Cells["unit"].Value.ToString();
                //string pos = ((T_Combo)colPos.Items[0]).Value1;
                string pos = "";
                foreach (var item in colPos.Items)
                {
                    var combo = (T_Combo)item;
                    if (combo.Value2 == "是")
                    {
                        pos = combo.Value1;
                        break;
                    }
                }
                decimal subAmount = Convert.ToDecimal(dgvProduct.CurrentRow.Cells["SubAmount"].Value);
                storeItems.Add(new V_StoreIOItem
                {
                    ProductId = id,
                    Name = name,
                    Price = inPrice,
                    Amount = 1,
                    Unit = unit,
                    Pos2 = pos,
                    SubAmount = subAmount

                });

                dgvProductOut.DataSource = null;
                dgvProductOut.DataSource = storeItems;
                lblCount.Text = dgvProductOut.RowCount.ToString();
            }
        }

        private void btnDeleteItem_Click(object sender, EventArgs e)
        {
            if (dgvProductOut.CurrentRow != null)
            {
                var row = dgvProductOut.SelectedRows[0];
                string id = row.Cells["colId"].Value.ToString();
                var storeItem = storeItems.Where<V_StoreIOItem>(s => s.ProductId == id).FirstOrDefault();
                storeItems.Remove(storeItem);
                dgvProductOut.DataSource = null;
                dgvProductOut.DataSource = storeItems;
                lblCount.Text = dgvProductOut.RowCount.ToString();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (dgvProductOut.Rows.Count == 0)
            {
                FormSysMessage.ShowMessage("请选择商品！");
                return;
            }

            SetValue();
            if (rbExpend.Checked)
            {
                storeIO.BuzType = "耗材";
            }
            else if (rbReturn.Checked)
            {
                storeIO.BuzType = "向供应商退货";
            }
            else if (rbTransfer.Checked)
            {
                storeIO.BuzType = "调拨调出";
            }
            else if (rbInventoryShortages.Checked)
            {
                storeIO.BuzType = "盘亏";
                storeIO.Type = "盘点";
            }
            storeItems = (List<V_StoreIOItem>)dgvProductOut.DataSource;

            if (string.IsNullOrEmpty(storeIO.Id))
            {
                storeIO.Id = Guid.NewGuid().ToString("D");
                productBll.AddStoreIO(storeIO, storeItems, false);
            }
            else
            {
                productBll.UpdateStoreIO(storeIO, storeItems, false);
            }
            this.FindForm().Close();

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.FindForm().Close();
        }

        private void pbClose_Click(object sender, EventArgs e)
        {
            this.FindForm().Close();
        }

        private void dgvProduct_DoubleClick(object sender, EventArgs e)
        {

        }

        private void rbExpend_CheckedChanged(object sender, EventArgs e)
        {
            if (rbExpend.Checked)
            {
                cmbProvider.Enabled = false;
            }
            else
            {
                cmbProvider.Enabled = true;
            }
        }

        private void rbInventoryShortages_CheckedChanged(object sender, EventArgs e)
        {
            if (rbInventoryShortages.Checked)
            {
                cmbProvider.Enabled = false;
            }
            else
            {
                cmbProvider.Enabled = true;
            }
        }

        private void PnlInfoTitle_MouseDown(object sender, MouseEventArgs e)
        {
            Drog = true;
            Top = e.Y;
            Left = e.X;
        }

        private void PnlInfoTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (!Drog) return;
            var findForm = FindForm();
            if (findForm == null) return;
            findForm.Top += e.Y - Top;
            findForm.Left += e.X - Left;
        }

        private void PnlInfoTitle_MouseUp(object sender, MouseEventArgs e)
        {
            Drog = false;
        }


    }
}
